package broker_dao

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Database/admin/phone"
	"hft/Http/Services/broker/broker_utils"
	"hft/e"
	"hft/tools/phone/api"
	"hft/tools/phone/model"
	"strings"

	"gorm.io/gorm"
)

// 清除绑定了该经纪人的目的码关于该经纪人的信息
func ClearPhone(db *gorm.DB, brokerPhone string, managerPhone string) (err error) {
	var phoneList []*phone.PhoneAudio
	db.Where("broker LIKE ?", fmt.Sprintf("%%,%v,%%", brokerPhone)).Find(&phoneList) // 先删除掉没有再添加序列而且绑定了该经纪人的楼盘的400记录
	if len(phoneList) != 0 {
		var phones []*model.Row
		// 更新当前远端经纪人手机号
		for _, v := range phoneList {
			ani, dni := broker_utils.IsNeedAddAudio(v.Audit, v.ID)
			var newBroker = broker_utils.BrokerPhone(managerPhone, v.Broker, brokerPhone)
			phones = append(phones, &model.Row{Dn: fmt.Sprintf("%v", v.ID), AniVoiceName: ani, DniVoiceName: dni, TransType: "rnd", Tel: newBroker})
		}
		// 更新远端手机
		if code := api.PhoneVirtual.AddOrEditPhone(phones); code != "0" {
			return errors.New(e.Phone400AddFail)
		}
		var sql = fmt.Sprintf("UPDATE hft_phone_audio SET broker = CASE WHEN broker = ',%v,' THEN  ',%v,' WHEN broker LIKE '%%,%%,%%' THEN REPLACE(broker, ',%v,', ',') ELSE broker END;", brokerPhone, managerPhone, brokerPhone)
		// 如果成功了就批量更新表
		if err = db.Exec(sql).Error; err != nil {
			return errors.New(e.ErrorInfo)
		}
	}
	return nil
}

// 判断是否绑定了楼盘 有就绑定，没有就不绑定
func BindLouPanPhone(db *gorm.DB, louList []*admin.LouPan, brokerPhone string, managerPhone string) (err error) {
	if err := ClearPhone(db, brokerPhone, managerPhone); err != nil {
		return err
	}
	if len(louList) != 0 {
		// 如果有楼盘需要添加 就加上
		var ids []uint
		var idsStr []string
		for _, v := range louList {
			ids = append(ids, v.ID)
			idsStr = append(idsStr, fmt.Sprintf("%v", v.ID))
		}
		var louPhone []*phone.PhoneAudio
		var modelLouPhone []*model.Row
		db.Where("lou_id IN (?)", ids).Find(&louPhone)
		for _, v := range louPhone {
			ani, dni := broker_utils.IsNeedAddAudio(v.Audit, v.ID)
			var newBroker = broker_utils.AddNewBroker(managerPhone, v.Broker, brokerPhone)
			modelLouPhone = append(modelLouPhone, &model.Row{Dn: fmt.Sprintf("%v", v.ID), AniVoiceName: ani, DniVoiceName: dni, TransType: "rnd", Tel: newBroker})
		}
		// 更新远端手机
		if code := api.PhoneVirtual.AddOrEditPhone(modelLouPhone); code != "0" {
			return errors.New(e.Phone400AddFail)
		}
		// 更新表
		if err = db.Exec(fmt.Sprintf("UPDATE hft_phone_audio SET broker = CASE WHEN broker = ',%v,' AND lou_id IN (%v)  THEN ',%v,' WHEN broker LIKE '%%,%%,%%' AND lou_id IN (%v) THEN CONCAT(broker, '%v,') ELSE broker END;", managerPhone, strings.Join(idsStr, ","), brokerPhone, strings.Join(idsStr, ","), brokerPhone)).Error; err != nil {
			return errors.New(e.ErrorInfo)
		}
	}
	return nil
}
